import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue')
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('../views/ProductDetailView.vue')
  },
  {
    path: '/publish',
    name: 'Publish',
    component: () => import('../views/PublishView.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/CategoryView.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/ProfileView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 检查用户是否已登录
router.beforeEach((to, from, next) => {
  // 需要认证的路由
  const authRequiredRoutes = ['/profile', '/publish', '/cart']
  
  // 检查是否访问需要认证的路由
  if (authRequiredRoutes.includes(to.path)) {
    const token = localStorage.getItem('token')
    
    if (!token) {
      // 未登录，重定向到登录页
      ElMessage.warning('请先登录后再访问')
      next('/login')
      return
    }
  }
  
  next()
})

export default router